<template>
  <div class="mod-info">
    <div class="grid-content bg-purple-dark">
      <el-form ref="form" :model="form" :rules="dataRule" label-width="140px" class="demo-ruleForm">
        <div>
          <div class="bold">主体信息</div>
          <el-form-item label="企业名称">
            <el-input v-model="form.company_name" disabled></el-input>
          </el-form-item>
          <el-form-item label="统一信用代码">
            <el-input v-model="form.credit_code" disabled></el-input>
          </el-form-item>
          <el-form-item label="经营范围">
            <el-input v-model="form.business_scope" disabled></el-input>
          </el-form-item>
          <el-form-item label="企业所在地区">
            <el-input v-model="form.province" disabled></el-input>
          </el-form-item>
          <el-form-item label="详情地址">
            <el-input v-model="form.company_address" disabled></el-input>
          </el-form-item>
        </div>

        <div>
          <!-- <div>法人信息</div> -->
          <el-form-item label="法人姓名">
            <el-input v-model="form.legal_representative" disabled></el-input>
          </el-form-item>
          <el-form-item label="证件类型">
            <el-radio v-model="form.id_type" :label="0" disabled>身份证</el-radio>
            <el-radio v-model="form.id_type" :label="1" disabled>护照</el-radio>
          </el-form-item>
          <el-form-item label="法人证件号码">
            <el-input v-model="form.id_number" disabled></el-input>
          </el-form-item>
          <el-form-item label="法人手机号">
            <el-input v-model="form.lr_mobile" maxlength="11" show-word-limit disabled></el-input>
          </el-form-item>
          <el-form-item label="法人邮箱">
            <el-input type="email" v-model="form.lr_email" disabled></el-input>
          </el-form-item>
        </div>

        <div>
          <!-- <div>上传附件</div> -->
          <el-form-item label="营业执照">
            <img class="table-img mr10" v-for="(item, i) in businessLicenseImages" :key="i" :src="item" />
          </el-form-item>
          <el-form-item label="法人身份证正反面">
            <img class="table-img mr10" v-for="(item, i) in identtyImages" :key="i" :src="item" />
          </el-form-item>
        </div>
        <div class="bold">店铺信息</div>
        <el-form-item label="商户名称" prop="shop_name" :rules="[{ required: true, message: '商户名称不能为空' }]">
          <el-input v-model="form.shop_name" maxlength='16'></el-input>
        </el-form-item>
        <el-form-item label="省市区" prop="province_name" :rules="[{ required: true, message: '省市区不能为空' }]">
          <el-cascader ref="refSubCat" v-model="provinces" :options="options" :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%;"></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="所属街道" prop="street_code" :rules="[ { required: true, message: '所属街道不能为空'}]">
          <el-select v-model="form.street_code" placeholder="请选择" @change="streetChange">
            <el-option v-for="(v,i) in streetList" :key="i" :label="v.label" :value="v.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属社区" prop="community_code" :rules="[ { required: true, message: '所属社区不能为空'}]">
          <el-select v-model="form.community_code" placeholder="请选择" @change="communityChange">
            <el-option v-for="item in communityList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商户地址" prop="address" :rules="[{ required: true, message: '商户地址不能为空' }]">
          <el-input v-model="form.address" maxlength='100' v-on:input="getAddressKeyword"></el-input>
        </el-form-item>
        <!-- 地图 -->
        <div id="container" style="width:100%; height:300px"></div>

        <el-form-item label="商业主体名称" prop="main_name" :rules="[{ required: true, message: '商业主体名称不能为空' }]">
          <el-input v-model="form.main_name" maxlength='20'></el-input>
        </el-form-item>

        <el-form-item label="商户LOGO" prop="logo" :rules="[{ required: true, message: '商户LOGO不能为空' }]">
          <Imglist @updataImg='updataImg' :limit="1" :value="formLogo" :clearVisible="clearVisible"></Imglist>

        </el-form-item>
        <el-form-item label="门店图片" prop="store_images" :rules="[{ required: true, message: '请上传门店图片' }]">
          <Imglist @updataImg='uploadStoreImages' :limit="2" :value="storeImages" :clearVisible="clearVisible"></Imglist>
        </el-form-item>
        <el-form-item label="客服电话" prop="customer_service_phone" :rules="[{ required: true, message: '客服电话不能为空' }]">
          <el-input v-model.number="form.customer_service_phone" maxlength='11'></el-input>
        </el-form-item>
        <el-form-item label="商户简介" prop="remark" :rules="[{ required: true, message: '商户简介不能为空' }]">
          <el-input type="textarea" v-model="form.remark" maxlength='400'></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="business_hours" :rules="[{ required: true, message: '请选择营业时间' }]">
          <!-- <el-date-picker v-model="form.business_hours" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker> -->
          <el-checkbox-group v-model="businessHours">
            <el-checkbox label="周一"></el-checkbox>
            <el-checkbox label="周二"></el-checkbox>
            <el-checkbox label="周三"></el-checkbox>
            <el-checkbox label="周四"></el-checkbox>
            <el-checkbox label="周五"></el-checkbox>
            <el-checkbox label="周六"></el-checkbox>
            <el-checkbox label="周日"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="时间段" prop="time_quantum" :rules="[{ required: true, message: '请选择时间段' }]">
          <el-time-select placeholder="起始时间" v-model="startTime" :picker-options="{
            start: '00:00',
            step: '00:30',
            end: '23:30'
          }">
          </el-time-select>
          <el-time-select placeholder="结束时间" v-model="endTime" :picker-options="{
            start: '00:00',
            step: '00:30',
            end: '23:30',
            minTime: startTime
          }">
          </el-time-select>
        </el-form-item>

        <el-form-item label="场地说明" prop="place_remark" :rules="[{ required: true, message: '场地说明不能为空' }]">
          <el-input type="textarea" v-model="form.place_remark" maxlength='200'></el-input>
        </el-form-item>
        <el-form-item v-if="form.union_business" label="打赏比例（%）" prop="reward_ratio">
          <el-input-number v-model="form.reward_ratio" :min="0" :max="100" :precision="2" placeholder="请输入"></el-input-number>
          <span class="mlr">%</span>
        </el-form-item>
        <el-form-item v-if="form.union_business" label="优惠信息" prop="special_offers">
          <el-input type="textarea" v-model="form.special_offers" maxlength='200'></el-input>
        </el-form-item>
        <div>
          <div class="bold">
            运营人信息
          </div>
          <el-form-item label="姓名" prop="loser" :rules="[{ required: true, message: '姓名不能为空' }]">
            <el-input v-model="form.loser" maxlength='5'></el-input>
          </el-form-item>
          <el-form-item label=" 手机号码" prop="mobile">
            <el-input v-model="form.mobile" maxlength='11'></el-input>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">{{ form.id ? '提交修改' : '确定提交' }} </el-button>

        </el-form-item>
      </el-form>
    </div>
    <!-- </el-col> -->
    <!-- </el-row> -->
  </div>
</template>

<script>
import { isEmail, isMobile } from '@/utils/validate'
import seviceApi from '@/api/serviceApi.js'
import Imglist from './../../oss/oss-uploadImg2'
import axios from 'axios'
import qqmapPlus from 'qqmap-plus'
export default {
  components: {
    Imglist,
  },
  data () {
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      formLogo: [], // 店铺logo
      storeImages: [], // 店铺图片
      businessLicenseImages: [], // 回显营业执照
      identtyImages: [], // 回显身份证
      form: {
        id: '',
        company_name: '',
        credit_code: '',
        business_scope: '',
        province: '',
        company_address: '',
        legal_representative: '',
        id_type: '',
        id_number: '',
        lr_mobile: '',
        lr_email: '',
        business_license_images: '',
        identty_images: '',
        logo: '',
        store_images: '',
        shop_name: null,
        province_code: null,
        city_code: null,
        area_code: null,
        province_name: '',
        city_name: '',
        area_name: '',
        address: null,
        main_name: null,
        customer_service_phone: null,
        remark: null,
        time_quantum: null,
        business_hours: null,
        place_remark: null,
        loser: null,
        mobile: null,
        tx_longitude: null, // 经度
        tx_latitude: null, // 纬度
        street_code: null
      },
      businessHours: [], // 时间
      startTime: '',
      endTime: '',
      clearVisible: false,
      options: [],
      provinces: [],
      // 腾讯地图
      map: null,
      getAddress: '湖北省武汉市江夏区光谷世贸中心',
      getAddCode: null,
      addressKeyword: '',
      shopInfo: {
        lng: '114.4216',
        lat: '30.471861'
      },
      dataRule: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      streetList: [],
      communityList: [],
      setTime: null
    }
  },
  mounted () {
    this.getProvinces()
    this.getShop()
  },
  methods: {
    // 上传图片logo
    updataImg (e) {
      this.form.logo = e
    },
    // 上传门店图片
    uploadStoreImages (e) {
      this.form.store_images = e
    },
    getShop () {
      seviceApi.getYxtShopInfo().then(res => {
        if (res && res.data.code == 200) {
          if (res.data.data.logo) {
            this.formLogo = res.data.data.logo.split(',')
          }
          if (res.data.data.tx_latitude) {
            this.shopInfo.lat = res.data.data.tx_latitude
            this.shopInfo.lng = res.data.data.tx_longitude
          }
          if (res.data.data.business_license_images) {
            this.businessLicenseImages = res.data.data.business_license_images.split(',')
          }
          if (res.data.data.identty_images) {
            this.identtyImages = res.data.data.identty_images.split(',')
          }
          if (res.data.data.store_images) {
            this.storeImages = res.data.data.store_images.split(',')
          }
          if (res.data.data.business_hours) {
            this.businessHours = res.data.data.business_hours.split(',')
          }
          if (res.data.data.time_quantum) {
            this.startTime = res.data.data.time_quantum.split('-')[0]
            this.endTime = res.data.data.time_quantum.split('-')[1]
          }
          this.form = res.data.data;
          this.provinces = [res.data.data.province_code, res.data.data.city_code, res.data.data.area_code]
          this.getStreetList(this.form.area_code)
          this.getCommunityList()
          this.init()
        }
      })
    },
    init () {
      var that = this
      // EXUBZ-5PT6U-ZF5VL-2BM27-ZOST7-VYFIP
      // KNZBZ-YSB3S-QGNOH-6UN4N-LVGUZ-OJFPQ
      qqmapPlus.init('TBYBZ-WT2W6-4RXSK-E234N-BH7S7-VGBJ4', () => {
        var myLatlng = new qq.maps.LatLng(this.shopInfo.lat, this.shopInfo.lng)
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        }
        that.map = new qq.maps.Map(
          document.getElementById('container'),
          myOptions
        )
        var marker = new qq.maps.Marker({
          position: myLatlng,
          map: that.map
        })
        //   var map = new qq.maps.Map(document.getElementById("container"),{
        //     zoom: 16,
        //     center: myLatlng,
        //   })
        //   var info = new qq.maps.InfoWindow({map:that.map});
        //  qq.maps.event.addListener(marker,'click',function(evt) {
        //   info.open();
        // 	info.setContent();
        // 	info.setPosition(new qq.maps.LatLng(evt.latLng.getLat(),evt.latLng.getLng()));
        //  });

        // 获取点击后的地址
        qq.maps.event.addListener(that.map, 'click', function (event) {
          // 获取点击后的地图坐标
          if (marker) {
            marker.setMap(null)
            marker = null
          }
          that.shopInfo.lng = event.latLng.getLng()
          that.shopInfo.lat = event.latLng.getLat()
          marker = new qq.maps.Marker({
            position: new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng()),
            map: that.map
          })
          that.getAddressCode()
        })

      })
    },
    // 获取街道列表
    getStreetList (code) {
      seviceApi.streetList(code).then(res => {
        if (res && res.data.code == 200) {
          this.streetList = res.data.list
        }
      })
    },
    streetChange (e) {
      this.form.community_code = ""
      this.getCommunityList()
      for (let i = 0; i < this.streetList.length; i++) {
        if (this.streetList[i].value == e) {
          this.form.street_name = this.streetList[i].label;
          break
        }
      }
    },
    // 获取社区列表
    getCommunityList () {
      if (!this.form.street_code) {
        this.communityList = []
      } else {
        seviceApi.streetList(this.form.street_code).then(res => {
          if (res && res.data.code == 200) {
            this.communityList = res.data.list
          }
        })
      }
    },
    communityChange (e) {
      for (let i = 0; i < this.communityList.length; i++) {
        if (this.communityList[i].value == e) {
          this.form.community_name = this.communityList[i].label;
          break
        }
      }
    },
    // 通过地址获得位置
    getAddressKeyword () {
      var that = this;
      if (that.setTime) clearTimeout(that.setTime)
      let address = that.form.province_name + that.form.city_name + that.form.area_name + that.form.address
      seviceApi.mapAddressgetcode(address).then(res => {
        if (res && res.data.code == 200) {
          that.form.tx_longitude = res.data.date.location.lng;
          that.form.tx_latitude = res.data.date.location.lat;
          that.setTime = setTimeout(() => {
            that.shopInfo.lng = res.data.date.location.lng;
            that.shopInfo.lat = res.data.date.location.lat;
            that.init()
          }, 1000)
        }
      })
    },
    // 通过坐标获得地址
    getAddressCode () {
      var that = this
      var lat = parseFloat(this.shopInfo.lat)
      var lng = parseFloat(this.shopInfo.lng)
      var latLng = new qq.maps.LatLng(lat, lng)
      this.shopInfo.lat = latLng.lat
      this.shopInfo.lng = latLng.lng
      let location = latLng.lat + ',' + latLng.lng
      seviceApi.mapAddress(location).then(res => {
        that.form.address = res.data.date.formatted_addresses.rough
        var adcode = res.data.date.ad_info.adcode
        that.form.tx_longitude = res.data.date.location.lng,
          that.form.tx_latitude = res.data.date.location.lat
        // 根据区的经纬度查询省市区
        seviceApi.getlbsPat(adcode).then(res => {
          if (res && res.data.code == 200) {
            if (res.data.list.length == 2) {
              that.form.province_code = res.data.list[0].value,
                that.form.province_name = res.data.list[0].label
              that.form.area_code = res.data.list[1].value
              that.form.area_name = res.data.list[1].label
              that.provinces = [res.data.list[0].value, res.data.list[1].value]
            } else {
              that.form.province_code = res.data.list[0].value,
                that.form.province_name = res.data.list[0].label
              that.form.city_code = res.data.list[1].value
              that.form.city_name = res.data.list[1].label
              that.form.area_code = res.data.list[2].value
              that.form.area_name = res.data.list[2].label
              that.provinces = [res.data.list[0].value, res.data.list[1].value, res.data.list[2].value]
            }
          }
        })
      })
    },

    // 获取省市区
    getProvinces () {
      seviceApi.getCnareaTreelbs().then(res => {
        if (res && res.data.code == 200) {
          this.options = res.data.tree.children
        }
      })
    },
    // 提交
    onSubmit (form) {
      if (this.businessHours) {
        this.form.business_hours = this.businessHours.join(',')
      }
      if (!this.form.reward_ratio) this.form.reward_ratio = 0
      // 拼接时间段
      this.form.time_quantum = this.startTime + '-' + this.endTime
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.form.logo) {
            if (typeof (this.form.logo) === 'string') {
              this.form.logo = this.form.logo
            } else {
              this.form.logo = this.form.logo.join(',')
            }
          }
          if (this.form.store_images) {
            if (typeof (this.form.store_images) === 'string') {
              this.form.store_images = this.form.logo
            } else {
              this.form.store_images = this.form.store_images.join(',')
            }
          }
          if (this.form.id == '') {
            seviceApi.saveInitializeShop(this.form).then(res => {
              if (res && res.data.code == 200) {
                this.$message({
                  showClose: true,
                  message: '提交成功，请等待平台审核',
                  type: 'success'
                })
                this.clearVisible = true
              }
            })
          } else {
            seviceApi.updateInitializeShoptwo(this.form).then(res => {
              if (res && res.data.code == 200) {
                this.$message({
                  showClose: true,
                  message: '提交成功，请等待平台审核',
                  type: 'success'
                })
                this.clearVisible = true
              }
            })
          }
        }
      })
    },
    // 省市区选择
    handleChange (value) {
      this.provinces = value
      if (value.length == 2) {
        this.form.province_code = value[0],
          this.form.province_name = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0]
        this.form.area_code = value[1]
        this.form.area_name = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1]
      } else {
        this.form.province_code = value[0],
          this.form.province_name = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0]
        this.form.city_code = value[1]
        this.form.city_name = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1]
        this.form.area_code = value[2]
        this.form.area_name = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2]
      }
      this.form.street_code = "";
      this.form.community_code = ""
      this.getStreetList(this.form.area_code)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  margin: 0 auto;
}

#container {
  /*地图(容器)显示大小*/
  margin-bottom: 20px;
}

.table-img {
  width: 146px;
  height: 146px;
}

.el-scrollbar__wrap {
  margin-right: 0px !important;
}

.mlr {
  margin-left: 20px;
  margin-right: 20px;
}
</style>
